from sqlalchemy import Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from init.mysql import engine

Base = declarative_base()


class StockFundFlow(Base):
    __tablename__ = 'stock_fund_flow'
    id = Column(Integer, primary_key=True, autoincrement=True)
    code = Column(String(6))
    t = Column(String(10))
    zdf = Column(String(10))
    hsl = Column(String(10))
    jlr = Column(String(20))
    jlrl = Column(String(10))
    zljlr = Column(String(20))
    zljlrl = Column(String(10))
    hyjlr = Column(String(20))
    hyjlrl = Column(String(10))

    def __init__(self, code, t, zdf, hsl, jlr, jlrl, zljlr, zljlrl, hyjlr, hyjlrl):
        self.code = code
        self.t = t
        self.zdf = zdf
        self.hsl = hsl
        self.jlr = jlr
        self.jlrl = jlrl
        self.zljlr = zljlr
        self.zljlrl = zljlrl
        self.hyjlr = hyjlr
        self.hyjlrl = hyjlrl

    @staticmethod
    def insert_or_update(code, data_list):
        session = sessionmaker(bind=engine)()
        for data in data_list:
            existing_stock_fund_flow = session.query(StockFundFlow).filter_by(code=code, t=data['t']).first()
            if existing_stock_fund_flow:
                existing_stock_fund_flow.zdf = data['zdf']
                existing_stock_fund_flow.hsl = data['hsl']
                existing_stock_fund_flow.jlr = data['jlr']
                existing_stock_fund_flow.jlrl = data['jlrl']
                existing_stock_fund_flow.zljlr = data['zljlr']
                existing_stock_fund_flow.zljlrl = data['zljlrl']
                existing_stock_fund_flow.hyjlr = data['hyjlr']
                existing_stock_fund_flow.hyjlrl = data['hyjlrl']
            else:
                session.add(StockFundFlow(code=code, t=data['t'], zdf=data['zdf'], hsl=data['hsl'], jlr=data['jlr'],
                                          jlrl=data['jlrl'], zljlr=data['zljlr'], zljlrl=data['zljlrl'],
                                          hyjlr=data['hyjlr'], hyjlrl=data['hyjlrl']))
        session.commit()
        session.close()


Base.metadata.create_all(engine)
